#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<arpa/inet.h>

int main(){
    // 1. 创建通信的套接字
    int fd = socket(AF_INET, SOCK_STREAM, 0);
    if(fd == -1){
        perror("socket");
        return -1;
    }
    // 2. 绑定
    struct sockaddr_in saddr;
    saddr.sin_family = AF_INET;
    saddr.sin_port = htons(9999);
    //saddr.sin_addr.s_addr = INADDR_ANY; // 0 = 0.0.0.0
    // 转大端
    inet_pton(AF_INET,"127.0.0.1",&saddr.sin_addr.s_addr);
    int ret = connect(fd, (struct sockaddr*)&saddr, sizeof(saddr));
    if( ret == -1){
        perror("connect");
        return -1;
    }

    int number = 0;
    // 3. 通信
    while(1){
        char recvbuf[1024];
        sprintf(recvbuf, "hello, I am client %d", number++);
        send(fd,recvbuf, strlen(recvbuf)+1, 0);

         // 清空缓存区，将接收到的数据存到buff
        memset(recvbuf, 0, sizeof(recvbuf));
        
        // 接收
        int len = recv(fd, recvbuf, sizeof(recvbuf), 0);
       
        if(len > 0 ){
            printf("server say%s\n", recvbuf);
        }
        else if(len == 0){ // 服务端断开连接
            printf("服务器断开连接\n");
            break;
        }
        else{
            perror("recv");
            break;
        }
        sleep(1);
    }

    // g关闭
    close(fd);
    return 0;
}